package FloodFill;

import java.util.*;

/**
 * @description:
 * @author: ywk
 * @date: 2020-12-30
 */
public class 区间合并 {
    static List<List<Integer>> merge(int[][] nums) {
        List<List<Integer>> list = new ArrayList<>();
        Arrays.sort(nums, Comparator.comparingInt(o -> o[0]));
        List list1 = new ArrayList();
        list1.add(nums[0][0]);
        list1.add(nums[0][1]);
        list.add(list1);
        for (int i = 1; i < nums.length; i++) {
            int[] num = nums[i];
            Integer last = list.get(list.size() - 1).get(1);
            if (num[0] <= last) {
                list.get(list.size() - 1).set(1, Math.max(last, num[1]));
            } else {
                list1 = new ArrayList();
                list1.add(num[0]);
                list1.add(num[1]);
                list.add(list1);
            }
        }
        return list;
    }
    public static ArrayList<Interval> merge(ArrayList<Interval> intervals) {
        Collections.sort(intervals, Comparator.comparingInt(o -> o.start));
        ArrayList<Interval> result = new ArrayList<>();
        result.add(intervals.get(0));
        for (int i = 1; i < intervals.size() ; i++) {
            //取最后一个
            Interval pre = result.get(result.size() - 1);
            Interval next = intervals.get(i);
            if (pre.end >=next.start) {
                //合并
                result.set(result.size() - 1, new Interval(pre.start,
                        Math.max(pre.end,next.end)));
            }else{
                result.add(next);
            }
        }
        return result;
    }



    public static void main(String[] args) {
//        System.out.println(merge(new int[][]{{1, 3}, {2, 6}, {7, 9}}));
        System.out.println(merge(new ArrayList(Arrays.asList(new Interval[]{new Interval(10, 30), new Interval(20, 60),
                new Interval(80, 100), new Interval(150, 180)}))));

    }
}

